<?php

class Product extends AppModel {

    public $name = 'Product';
    public $useTable = 'product';
    public $primaryKey = 'product_id';
    public $hasMany = array(
        'product_language' => array(
            'className' => 'Productlanguage',
            'foreignKey' => 'product_id',
        )
    );
    public $validate = array(
        /*'price' => array(
            'rule' => 'Numeric'
        ),*/
        'image' => array(
            'extension'=>array(
                'rule' => array('extension',array('png','gif','jpg')),
                'message' => 'Please selecte txt file',
            ),
             'between' => array(
                'rule'    => 'notEmpty',
                'message' => 'This field cannot be left blank'
            )
        ),
        'product_type' => array(
            'rule' => 'notEmpty'
        )
    );

    function beforeValidate($options = array()) {
        parent::beforeValidate($options);
        App::import('model', 'Productlanguage');
        $ob = new Productlanguage();
        $ob->set($this->data);
        if ($ob->validates()) {
            $file = $this->data['Product']['image'];
            
            if (isset($file['error']) && !$file['error']) {
                $upload_dir = APP . 'webroot' . DS . 'images' . DS . 'uploads' . DS. 'products' . DS;
                $filename = basename($file['name']);
                @move_uploaded_file($file['tmp_name'], $upload_dir . $filename);
                if(file_exists($upload_dir . $filename)){
                    chmod($upload_dir . $filename, 0777);
                }
                $this->data['Product']['image'] = $filename;
            }
            return true;
        }
        return false;
    }
    
    
    /**
     * 
     * @param type $array_images
     * @param type $product_id
     * @return boolean
     */
    
    public function addMultiImages($array_images,$product_id){
        App::import('model', 'ProductImage');
        $ob = new ProductImage();
        $upload_dir = APP . 'webroot' . DS . 'images' . DS . 'uploads' . DS. 'products' . DS;
        if(is_array($array_images)){
            foreach($array_images as $key=>$value){
                $file = $value['value'];
                if (!$file['error']) {
                    $ob->create();
                    $filename = basename($file['name']);
                    @move_uploaded_file($file['tmp_name'], $upload_dir . $filename);
                    if(file_exists($upload_dir . $filename)){
                        chmod($upload_dir . $filename, 0777);
                    }
                    $arrInsert = array('product_id' => $product_id, 'url' => $filename);
                    $ob->save(array('ProductImage' => $arrInsert));
                }
            }
        }
    }

    /**
     * 
     * @param type $created
     * @param type $options
     */
    public function afterSave($created, $options = array()) {
        parent::afterSave($created, $options);

        App::import('model', 'Productlanguage');
        App::import('model', 'Language');
        $ob = new Productlanguage();
        $data = $this->data;
        if ($created) {
            $data['Productlanguage']['product_id'] = $data['Product']['product_id'];
            foreach (Language::getList() as $language) {
                $ob->create();
                $data['Productlanguage']['language_id'] = $language;
                $ob->save($data);
            }
        } else {
            
            $data['Productlanguage']['language_id'] = Configure::read('Config.language');
            $data['Productlanguage']['product_id'] = $data['Product']['product_id'];
            if($id = $ob->findPrimaryKey(array('Productlanguage.language_id' => Configure::read('Config.language'),'Productlanguage.product_id' => $data['Product']['product_id']))){
                   $ob->id = $id;
                   $ob->save($data);
            }
        }
    }

    /**
     * get Product byID
     * @param type $categoryID
     * @return boolean
     */
    public function getProductID($productID) {
        $ob = new Product();
        $ob->hasMany['product_language']['conditions'] = array('product_language.language_id' => Configure::read('Config.language'));
        $result = $ob->findByproduct_id($productID);
        
        if ($result) {
            $result['Productlanguage'] = $result['product_language'][0];
            return $result;
        }
        else
            return false;
    }
    public function getAllProduct(){
        $ob = new Product();
        
        $ob->hasMany['product_language']['conditions'] = array('product_language.language_id' => Configure::read('Config.language'));
        $result = $ob->find('all');
        
        return $result;
    }
    
    /**
     * 
     */
    public function getPropertyOfProduct($productType,$product_id){
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        
        $return = array();
        $sql = "select PropertyLanguage.name property_name,Property.property_id property_id ,Property.type type";
        $sql .= " from product_type_property as ProductTypeProperty,property as Property,property_language as PropertyLanguage";
        $sql .= " WHERE ProductTypeProperty.property = Property.property_id AND Property.property_id = PropertyLanguage.property_id";
        $sql .= " AND  PropertyLanguage.language_id = 'eng' AND ProductTypeProperty.product_type = ?";
        $sql .= " order by  Property.oder ASC";
   
        $results = $this->getDataSource()->fetchAll($sql,array($productType));
        foreach ($results as $value) {
            if($value['Property']['type'] == 1){
                $return['ProductPropertyValue'][$value['Property']['property_id']] = $ob->getValueFromProductAndProperty($product_id,$value['Property']['property_id'],1);
            }
            if($value['Property']['type'] == 2){
                $return['ProductPropertyValueArr'][$value['Property']['property_id']] = $ob->getValueFromProductAndProperty($product_id,$value['Property']['property_id'],2);
            }
            if($value['Property']['type'] == 3){
                $return['ProductPropertyValueText'][$value['Property']['property_id']] = $ob->getValueFromProductAndProperty($product_id,$value['Property']['property_id'],3);
            }
            
        }
        //echo "<pre>";var_dump($return);die();
        return $return;
    }
    /**
     * Get list Product in Home order by Time limit 12
     * @return type
     */
    public function getProductHome($locationID,$offset = 0,$limit = 6){
        //echo $locationID;exit;
        //if($offset > 0)
            //$offset = $offset -1;
        $sql_limit = "LIMIT ".$offset.", ".$limit;
        
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        app::import('model', 'Location');
        $location = new Location();
        $arr_location = $location->getListChild($locationID);
        $condition_arr_location = implode(",",$arr_location);
        $condition = '';
        if($condition_arr_location){ 
            $condition .= " AND product.location_id in (".$condition_arr_location.")";
        }else{ 
            $condition .= " AND product.location_id = -1";
        }
        
        $condition .= " AND product.product_type <> ".ID_PRODUCT_TYPE_APT;
        
        $sql = "SELECT product.*, product_type.`name`, product_language.*
            FROM product, product_language, product_type
            WHERE product.product_type = product_type.id
            AND product_language.product_id = product.product_id
             ".$condition." 
            AND product_language.language_id = '".Configure::read('Config.language')."'
            ORDER BY product.created DESC ".$sql_limit;
        $results = $this->getDataSource()->fetchAll($sql);
        
        if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $property_arr= $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
				/*BEGIN SORT PROPERTY*/
				$array_view_property = array();
				if(is_array($property_arr) && isset($property_arr)){

                    if(isset($property_arr['ProductPropertyValueText']) && isset($property_arr['ProductPropertyValue'])){
					
                        $array_view_property = $property_arr['ProductPropertyValueText'];
						foreach($property_arr['ProductPropertyValue'] as $key_pval => $val_pval){
							$array_view_property[$key_pval] = $val_pval;
						}
                    }else if(isset($property_arr['ProductPropertyValueText'])){

                        $array_view_property =  $property_arr['ProductPropertyValueText'];

                    }
                    else{
                        $array_view_property = '';
                        if(isset($property_arr['ProductPropertyValue'])){  
                            $array_view_property =  $property_arr['ProductPropertyValue'];
                        }

                    }
                    $array_sort = array();
					
                    if(is_array($array_view_property) && isset($array_view_property)){
						
                        foreach($array_view_property as $key_order=>$value_order){
							$array_view_property[$key_order]['property_id'] = $key_order;
                            if(!isset($value_order['oder'])) $value_order['oder'] = 1000;

                            if($key_order == ID_PROPERTY_NAME_APT){

                                $array_name_apt = array();
								
								$language_echo = $value_order['property_language'];
								if(isset($value['product']['product_type'])){
									if($value['product']['product_type'] == ID_PRODUCT_TYPE_OFFICE){
										$language_echo = 'Name of Building';
									}
								}
                                $array_name_apt = array('name'=>$language_echo,'value'=>$value_order['property_value_language']);

                                unset($array_view_property[$key_order]);
                                $this->set('Property_name_apt', $array_name_apt);
                                continue;
                            }
                            array_push($array_sort, $value_order['oder']);
                        }
                        array_multisort($array_sort, SORT_ASC, $array_view_property);
                    }
                }
				/*END SORT PROPERTY*/
				$value['property_value'] = $array_view_property;
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
				
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    /**
     * get 1 product (Home->viewdetail)
     * @param type $productID
     * @return type
     */
    public function getProductViewID($productID){
        $results = array();
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        $sql = "SELECT product.*, product_type.`name`, product_language.*
            FROM product, product_language, product_type
            WHERE product.product_type = product_type.id
            AND product_language.product_id = product.product_id
            AND product_language.language_id = '".Configure::read('Config.language')."'
            AND product.product_id = ".$productID;
        $results = $this->getDataSource()->fetchAll($sql);
        
        //get property
        if(is_array($results)){
                $results[0]['property_value']  = $this->getPropertyOfProduct( $results[0]['product']['product_type'],$results[0]['product']['product_id']);
        }
        //get location
        $results[0]['location'] = $this->getLocationTrueLever($results[0]['product']['location_id']);
        App::import('model', 'ProductImage');
        $ob_image = new ProductImage();
        $results[0]['images'] = $ob_image->find('all',array('conditions' => array('product_id' => $productID)));
        //get category
        //App::import('model', 'Category');
        //$ob_category = new Category();
        //$results[0]['category'] = $ob_category->getCategoryID($results[0]['product']['category_id']);
        //print_r($results[0]['category']);exit;
        if(isset($results[0]['property_value']['ProductPropertyValueArr']) && is_array($results[0]['property_value']['ProductPropertyValueArr'])){
            $results[0]['multipleSelect'] = $this->generatePropertyMultiSelectOfProduct($results[0]['property_value']['ProductPropertyValueArr']);
        }
        return $results[0];
    }
	/**
     * get 1 product (Home->viewdetail) lang vn
     * @param type $productID
     * @return type
     */
	 public function getProductViewIDLangVN($productID){
        $results = array();
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        $sql = "SELECT product.*, product_type.`name`, product_language.*
            FROM product, product_language, product_type
            WHERE product.product_type = product_type.id
            AND product_language.product_id = product.product_id
            AND product_language.language_id = 'vn'
            AND product.product_id = ".$productID;
        $results = $this->getDataSource()->fetchAll($sql);

        //get location
        $results[0]['location'] =  $this->getLocationTrueLeverVN($results[0]['product']['location_id']);
        return $results[0];
    }
    /**
     * get District and city
     * @param type $location_id
     * @return type
     */
    public function getLocationTrueLever($location_id){
        $location_result = $this->getDataSource()->fetchAll("SELECT location.* FROM location WHERE location_id = ".$location_id);
        
        if($location_result){
            $district = $this->getDataSource()->fetchAll("SELECT location_language.`name` as name
                                        FROM location_language
                                        WHERE location_language.location_id = ". $location_result[0]['location']['location_id']."
                                        AND location_language.language_id = '".Configure::read('Config.language')."' ");
            $city = $this->getDataSource()->fetchAll("SELECT location_language.`name` as name
                                        FROM location_language
                                        WHERE location_language.location_id = ". $location_result[0]['location']['parent_id']."
                                        AND location_language.language_id = '".Configure::read('Config.language')."' ");
            
            return array('district'=>$district[0]['location_language']['name'],'city'=>$city[0]['location_language']['name']);
        }
        return array('district'=>'','city'=>'');
    }
	
	 public function getLocationTrueLeverVN($location_id){
        $location_result = $this->getDataSource()->fetchAll("SELECT location.* FROM location WHERE location_id = ".$location_id);
        
        if($location_result){
            $district = $this->getDataSource()->fetchAll("SELECT location_language.`name` as name
                                        FROM location_language
                                        WHERE location_language.location_id = ". $location_result[0]['location']['location_id']."
                                        AND location_language.language_id = 'vn' ");
            $city = $this->getDataSource()->fetchAll("SELECT location_language.`name` as name
                                        FROM location_language
                                        WHERE location_language.location_id = ". $location_result[0]['location']['parent_id']."
                                        AND location_language.language_id = 'vn' ");
            
            return array('district'=>$district[0]['location_language']['name'],'city'=>$city[0]['location_language']['name']);
        }
        return array('district'=>'','city'=>'');
    }
    
    /**
     *
     * @param type $productType
     * @param type $locationID
     * @param type $notID
     * @return type 
     */
    public function getListProductByLocationAndProductType($productType,$locationID,$notID){
      
       $results = $this->getDataSource()->fetchAll("SELECT product_language.*, product.* , product_type.`name` as producttype_name
                                                            FROM product,product_language, product_type
                                                            WHERE product.product_type = ".$productType."
                                                            #AND product.location_id = ".$locationID."
                                                            AND product.product_type = product_type.id 
                                                            AND product.product_id = product_language.product_id
                                                            GROUP BY product.product_id
                                                            ORDER BY product.created LIMIT 10 ");
       //if($location_result)  return $location_result;
       if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $allproperty_arr = $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
				$value['property_value'] = $this->getOrderListProperty($allproperty_arr,$value['product']['product_type']);
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
				
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    
    /**
     *
     * @param type $arr_search
     * @return type 
     */
    public function searchProperty(&$arr_search){
        $results = array();
        App::import('model', 'Location');
        $location = new Location();
        
        App::import('model', 'Category');
        $category = new Category();
        
        $condition = '';
        if(is_array($arr_search)){
            
            //category
            if($arr_search['category']){
                //get child category
                $categories = array();
                $category->getAllChildCategory($categories, $arr_search['category']);
               
                $condition .= " AND category_id in (" . implode(",", $categories).") ";
            }
            
            //location
            $arrayLocation = array();
			if(isset($arr_search['child_location']) && is_array($arr_search['child_location'])){
				foreach($arr_search['child_location'] as $key => $value){
					if($value){
						$arrayLocation[] = $key;
					}
				}
			}
            if(count($arrayLocation) > 0){
                $condition .= " AND product.location_id in (".  implode(",", $arrayLocation).")";
            }
            
            if($arr_search['location']){
                $list = $location->children($arr_search['location'], true);
                if(is_array($list)){
                    $array_new_data = array();
                    foreach ($list as $value) {
                        $array_new_data[] = $value['Location']['location_id'];
                    }
                }
                $condition_arr_location = implode(",",$array_new_data);
                if($condition_arr_location) 
                    $condition .= " AND product.location_id in (".$condition_arr_location.")";
                else 
                    $condition .= " AND product.location_id = -1";
            }
            
            
            //name
            if($arr_search['search_name']){
                $condition .= " AND product_language.`name` like '%".$arr_search['search_name']."%'";
            }
            
            //price
            if(is_numeric($arr_search['max_price']) || is_numeric($arr_search['min_price'])){
                if(is_numeric($arr_search['max_price']) && is_numeric($arr_search['min_price'])){
                    if($arr_search['max_price'] >= 0){
                        //swap
                        if($arr_search['max_price'] < $arr_search['min_price']){
                            $newPrice = $arr_search['max_price'];
                            $arr_search['max_price'] = $arr_search['min_price'];
                            $arr_search['min_price'] = $newPrice;
                        }
                        $condition .= " AND product.price <= ".$arr_search['max_price']."  AND product.price >= ".$arr_search['min_price'];
                    }else{
                       $condition .= " AND product.price >= ".$arr_search['min_price']; 
                    }
                }
                else if(is_numeric($arr_search['max_price'])){
                    if($arr_search['max_price'] >= 0){
                        $condition .= " AND product.price <= ".$arr_search['max_price'];
                    }else{
                        $condition .= " AND product.price >= ".$arr_search['max_price']* -1;
                    }
                    
                }else{
                    $condition .= " AND product.price >= ".$arr_search['min_price'];
                }
                 
            }
            //var_dump($condition);die();
            //bed room
            $has_min_bed = (isset($arr_search['bed_min']) && is_numeric($arr_search['bed_min']));
            $has_max_bed = (isset($arr_search['bed_max']) && is_numeric($arr_search['bed_max']));
            if($has_min_bed && $has_max_bed){
                if($arr_search['bed_max'] >= 0 && $arr_search['bed_max'] < $arr_search['bed_min']){
                    $new_bed = $arr_search['bed_max'];
                    $arr_search['bed_max'] = $arr_search['bed_min'];
                    $arr_search['bed_min'] = $new_bed;
                }
            }
            if($has_min_bed){
                $condition .=" AND (property_value.property_id = ".ID_PROPERTY_BED." AND property_value_language.value >= ".$arr_search['bed_min'].")";
            }
            if($has_max_bed){
                if($arr_search['bed_max'] >= 0)
                    $condition .=" AND (property_value.property_id = ".ID_PROPERTY_BED." AND property_value_language.value <= ".$arr_search['bed_max'].")";
                else{
                    if($has_min_bed){
                        //$condition .=" AND (property_value.property_id = ".ID_PROPERTY_BED." AND property_value_language.value <= ".($arr_search['bed_max'] * -1).")";
                    }else{
                        $condition .=" AND (property_value.property_id = ".ID_PROPERTY_BED." AND property_value_language.value >= ".($arr_search['bed_max'] * -1).")";
                    }
                }
            }
            //size
            $has_min_size = (isset($arr_search['size_min']) && is_numeric($arr_search['size_min']));
            $has_max_size = (isset($arr_search['size_max']) && is_numeric($arr_search['size_max']));
            if($has_min_size && $has_max_size){
                if($arr_search['size_max'] >= 0 && $arr_search['size_max'] < $arr_search['size_min']){
                    $new_size = $arr_search['size_max'];
                    $arr_search['size_max'] = $arr_search['size_min'];
                    $arr_search['size_min'] = $new_size;
                }
            }
            if($has_min_size){
                $condition .=" AND (property_value.property_id = ".ID_PROPERTY_MIN_SIZE." AND property_value_language.value >= ".$arr_search['size_min'].")";
            }
            if($has_max_size){
                if($arr_search['size_max'] >= 0)
                    $condition .=" AND (property_value.property_id = ".ID_PROPERTY_MIN_SIZE." AND property_value_language.value <= ".$arr_search['size_max'].")";
                else{
                    if($has_min_size){
                        //$condition .=" AND (property_value.property_id = ".ID_PROPERTY_MIN_SIZE." AND property_value_language.value <= ".($arr_search['size_max'] * -1).")";
                    }else{
                        $condition .=" AND (property_value.property_id = ".ID_PROPERTY_MIN_SIZE." AND property_value_language.value >= ".($arr_search['size_max'] * -1).")";
                    }
                }
            }
            
            
        }
        
        
        
        $sql = "SELECT product.*, product_language.`name`,property_value.*,property_value_language.*, product_type.`name`
                FROM product,product_language,product_property_value,property_value,property_value_language ,product_type
                WHERE product.product_id = product_language.product_id
                AND product.product_id = product_property_value.product_id
                AND product_property_value.property_value_id = property_value.property_value_id
                AND property_value_language.property_value_id = property_value.property_value_id
                AND product_language.language_id = ?  
                AND property_value_language.language_id = ? ".$condition."
                    
                AND product.product_type = product_type.id
                
                GROUP BY product.product_id";
        
        $results = $this->getDataSource()->fetchAll($sql,array(Configure::read('Config.language'),Configure::read('Config.language')));
        
        //return $location_result;
        if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $allproperty_arr = $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
				$value['property_value'] = $this->getOrderListProperty($allproperty_arr,$value['product']['product_type']);
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    
    /**
     *
     * @param type $arr_location
     * @return type 
     */
    public function searchlocation($arr_location,$categoryID=NULL){
        $results = array();
        App::import('model', 'Location');
        $location = new Location();
        App::import('model', 'Category');
        $category = new Category();
        
            
        $condition = '';
        $condition_location = implode(",",$arr_location);
        //echo $condition_location;exit;
        if($condition_location) $condition .= " AND product.location_id in (".$condition_location.")";
        else $condition .= " AND 1=1";
        
        //category
        if($categoryID){
            //get child category
            $categories = array();
           $category->getAllChildCategory($categories, $categoryID);
           $condition .= " AND product.category_id in (" . implode(",", $categories).") ";
        }
       
        $results = $this->getDataSource()->fetchAll("SELECT product.*, product_language.`name`, product_type.name
                                    FROM product,product_language ,product_type
                                    WHERE 1=1 
                                    AND product.product_type = product_type.id
                                    #AND product.category_id = ".ID_SERVEICED_APARTMENT."
                                    AND product.product_id = product_language.product_id
                                    AND product_language.language_id = '".Configure::read('Config.language')."' ".$condition);
        
        //return $location_result;
        if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $allproperty_arr = $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
				$value['property_value'] = $this->getOrderListProperty($allproperty_arr,$value['product']['product_type']);
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    
    public function searchname($search){
        $results = array();
        $results = $this->getDataSource()->fetchAll("SELECT product.*, product_language.`name`, product_type.name
                                    FROM product,product_language ,product_type
                                    WHERE product.product_type = product_type.id
                                    #AND product.product_type = ".ID_PRODUCT_TYPE_APT."
                                    AND product.product_id = product_language.product_id
                                    AND product_language.language_id = '".Configure::read('Config.language')."' 
                                    AND product_language.`name` like '%".$search."%'  ");
    
        //return $location_result;
        if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $allproperty_arr = $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
				$value['property_value'] = $this->getOrderListProperty($allproperty_arr,$value['product']['product_type']);
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    
    
    
    /**
     * Get list feature product
     * @return type
     */
    public function getFeatureProduct(){
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        $sql = "SELECT product.*, product_type.`name`, product_language.*
            FROM product, product_language, product_type
            WHERE product.product_type = product_type.id
            AND product_language.product_id = product.product_id
            AND product_language.language_id = '".Configure::read('Config.language')."'
            ORDER BY product.viewed DESC LIMIT 12";
        $results = $this->getDataSource()->fetchAll($sql);
        if(is_array($results)){
            $arr_return = array();
            foreach($results as $key=>$value){
                $value['property_value'] = $this->getPropertyOfProduct( $value['product']['product_type'],$value['product']['product_id']);
                $value['address_truelever'] = $this->getLocationTrueLever($value['product']['location_id']);
                $arr_return[] = $value;
            }
        }
        return $arr_return;
    }
    
    /**
     * 
     */
    public function generatePropertyMultiSelectOfProduct($propertyMultiSelect){
        App::import('model', 'PropertyValue');
        $ob = new PropertyValue();
        $return = array();
        foreach ($propertyMultiSelect as $key => $property){
            $return[$key]['property_name'] = $property['property_language'];
            $allPropertyValue = $ob->getValueFromProperty($key);
            foreach($allPropertyValue as $value){
                if(in_array($value['PropertyValue']['property_value_id'],$property['property_value'])){
                    $return[$key]['allValue'][] = array(
                        'property_value_name' => $value['PropertyValueLanguage']['value'],
                        'property_value_id' => $value['PropertyValue']['property_value_id'],
                        'is_check' => 1,
                    );
                }else{
                    $return[$key]['allValue'][] = array(
                        'property_value_name' => $value['PropertyValueLanguage']['value'],
                        'property_value_id' => $value['PropertyValue']['property_value_id'],
                        'is_check' => 0,
                    );
                }
            }
        }
        return $return;
    }
	
	public function getOrderListProperty($property,$product_type){
		$array_view_property = array();
		if(is_array($property) && isset($property)){
			if(isset($property['ProductPropertyValueText']) && isset($property['ProductPropertyValue'])){
				$array_view_property = $property['ProductPropertyValueText'];
				foreach($property['ProductPropertyValue'] as $key_pval => $val_pval){
					$array_view_property[$key_pval] = $val_pval;
				}
			}else if(isset($property['ProductPropertyValueText'])){
				$array_view_property =  $property['ProductPropertyValueText'];
			}
			else{
				$array_view_property = '';
				if(isset($property['ProductPropertyValue'])){  
					$array_view_property =  $property['ProductPropertyValue'];
				}
			}
			$array_sort = array();
			if(is_array($array_view_property) && isset($array_view_property)){
				foreach($array_view_property as $key_order=>$value_order){
					$array_view_property[$key_order]['property_id'] = $key_order;
					if(!isset($value_order['oder'])) $value_order['oder'] = 1000;

					if($key_order == ID_PROPERTY_NAME_APT){

						$array_name_apt = array();
						
						$language_echo = $value_order['property_language'];
						if(isset($product_type)){
							if($product_type == ID_PRODUCT_TYPE_OFFICE){
								$language_echo = __('Name of Building');
							}
						}
						$array_name_apt = array('name'=>$language_echo,'value'=>$value_order['property_value_language']);
						unset($array_view_property[$key_order]);
						$this->set('Property_name_apt', $array_name_apt);
						continue;
					}
					array_push($array_sort, $value_order['oder']);
				}
				array_multisort($array_sort, SORT_ASC, $array_view_property);
				return $array_view_property;
			}
		}
		else
			return $array_view_property;
	}
    
    /**
     * 
     */
    public function getProductByName($name){
        $return = array();
        $sql = "SELECT * FROM product_language as Productlanguage where Productlanguage.name like ? AND Productlanguage.language_id = ?";
        $results = $this->getDataSource()->fetchAll($sql,array("%".$name."%",Configure::read('Config.language')));
        foreach($results as $item){
            $return[] = array(
                'id' => $item['Productlanguage']['product_id'],
                'name' => $item['Productlanguage']['name'],
            );
        }
        return $return;
    }
    
    /*
     * 
     */
    public function getTitle($product){
        if(strlen($product['product_language']['seo_title']) > 0)
            return $product['product_language']['seo_title'];
        return $product['product_language']['name'];
    }
    
    /*
     * 
     */
    public function getSeoDescription($product){
        if(strlen($product['product_language']['seo_description']) > 0)
            return $product['product_language']['seo_description'];
        return $product['product_language']['name'];
    }
    
    /*
     * 
     */
    public function getSeoKeyword($product){
        if(strlen($product['product_language']['seo_keyword']) > 0)
            return $product['product_language']['seo_keyword'];
        return $product['product_language']['name'];
    }
    

}

